import os
import argparse
from data_generator import generate_and_save_data
from data_preprocessing import load_data, create_features, save_features
from model_training import load_features, prepare_data, train_model, evaluate_model, save_model
from prediction_service import app

def main():
    """用户复购预测工程主程序"""
    parser = argparse.ArgumentParser(description='用户复购预测工程')
    subparsers = parser.add_subparsers(dest='command')
    
    # 数据生成命令
    parser_data = subparsers.add_parser('generate_data', help='生成模拟数据')
    
    # 数据预处理命令
    parser_preprocess = subparsers.add_parser('preprocess', help='数据预处理')
    
    # 模型训练命令
    parser_train = subparsers.add_parser('train', help='训练模型')
    
    # 运行API服务命令
    parser_api = subparsers.add_parser('run_api', help='运行API服务')
    
    args = parser.parse_args()
    
    if args.command == 'generate_data':
        print("开始生成模拟数据...")
        generate_and_save_data()
        print("数据生成完成")
    
    elif args.command == 'preprocess':
        print("开始数据预处理...")
        customers, purchases = load_data()
        features = create_features(customers, purchases)
        save_features(features)
        print("数据预处理完成")
    
    elif args.command == 'train':
        print("开始模型训练...")
        features = load_features()
        X_train, X_test, y_train, y_test, feature_names, scaler = prepare_data(features)
        model = train_model(X_train, y_train, feature_names)
        metrics = evaluate_model(model, X_test, y_test)
        save_model(model, scaler, feature_names)
        print("模型训练完成")
    
    elif args.command == 'run_api':
        print("启动API服务...")
        app.run(host='0.0.0.0', port=5000)
    
    else:
        parser.print_help()

if __name__ == "__main__":
    main()    